package edu.kit.aifb.ldsbench.cli.util2;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.kit.aifb.ldstream.learner.out.xml.Tags;
import edu.kit.aifb.ldstream.stat.distrib.BinomialDistribution;
import edu.kit.aifb.ldstream.stat.distrib.ContinuousUniformDistribution;
import edu.kit.aifb.ldstream.stat.distrib.DiscreteUniformDistribution;
import edu.kit.aifb.ldstream.stat.distrib.ExponentialDistribution;
import edu.kit.aifb.ldstream.stat.distrib.IDistribution;
import edu.kit.aifb.ldstream.stat.distrib.NormalDistribution;
import edu.kit.aifb.ldstream.stat.distrib.PoissonDistribution;

final class DistributionXMLReader {

	private DistributionXMLReader(){}
	
	public static IDistribution readDistribution(Node n){
		
		Element e = (Element) n;
		String distribType = e.getAttribute(Tags.DISTRIBUTION_TYPE_TAG);
		
		IDistribution result = null;
		
		if(distribType.equals(Tags.BINOMIAL_DISTRIBUTION_TAG)){
			double p = textToDoubleValue(e.getElementsByTagName(Tags.P));
			int samples = (int) textToDoubleValue(e.getElementsByTagName(Tags.N));
			result = new BinomialDistribution(p, samples);
		} else if(distribType.equals(Tags.EXPONENTIAL_DISTRIBUTION_TAG)){
			double lambda = textToDoubleValue(e.getElementsByTagName(Tags.LAMBDA));
			result = new ExponentialDistribution(lambda);
		} else if(distribType.equals(Tags.NORMAL_DISTRIBUTION_TAG)){
			double sd = textToDoubleValue(e.getElementsByTagName(Tags.SD));
			double mean = textToDoubleValue(e.getElementsByTagName(Tags.MEAN));
			result = new NormalDistribution(mean, sd);
		} else if(distribType.equals(Tags.POISSON_DISRIBUTION_TAG)){
			double lambda2 = textToDoubleValue(e.getElementsByTagName(Tags.LAMBDA));
			result = new PoissonDistribution(lambda2);
		} else if(distribType.equals(Tags.CONTINUOUS_UNIFORM_DISTRIBUTION)){
			double max = textToDoubleValue(e.getElementsByTagName(Tags.MAX));
			double min = textToDoubleValue(e.getElementsByTagName(Tags.MIN));
			result = new  ContinuousUniformDistribution(min, max);
		} else if(distribType.equals(Tags.DISCRETE_UNIFORM_DISTRIBUTION_TAG)){
			double min2 = textToDoubleValue(e.getElementsByTagName(Tags.MIN));
			double max2 = textToDoubleValue(e.getElementsByTagName(Tags.MAX));
			result = new DiscreteUniformDistribution(min2, max2);
		}
		
		return result;
	}
	
	private static double textToDoubleValue(NodeList n){
		return Double.parseDouble(n.item(0).getTextContent());
	}
}
